package io.renren.modules.websocket.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.renren.modules.websocket.dao.WebsocketDao;
import io.renren.modules.websocket.entity.ChapterContentEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Service
@ServerEndpoint("/websocket/chapterContent/{chapterId}")
@Component

public class WebsocketController {
    Snowflake snowflake = new Snowflake(3L,10L);


    private static WebsocketDao websocketDao;

    @Autowired
    public void setWebsocketDao(WebsocketDao websocketDao){
        WebsocketController.websocketDao=websocketDao;
    }
    /**
     * 静态变量，
     * 用来记录当前在线连接数。
     * 应该把它设计成线程安全的。
     * */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，
     * 用来存放每个客户端对应的MyWebSocket对象。
     * */
    private static ConcurrentHashMap<String,WebsocketController> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，
     * 需要通过它来给客户端发送数据
     * */
    private Session session;
    /**
     * 接收chapterId
     * */
    private String chapterId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("chapterId") String chapterId) {
        System.out.println("打开链接！！！！"+chapterId);
        this.session = session;
        this.chapterId=chapterId;
        if(webSocketMap.containsKey(chapterId)){
            webSocketMap.remove(chapterId);
            webSocketMap.put(chapterId,this);
            //加入set中
        }else{
            webSocketMap.put(chapterId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        System.out.println("用户连接:"+chapterId+",当前在线人数为:" + getOnlineCount());


        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            System.out.println("用户:"+chapterId+",网络异常!!!!!!");
        }
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(chapterId)){
            webSocketMap.remove(chapterId);
            //从set中删除
            subOnlineCount();
        }
        System.out.println("用户退出:"+chapterId+",当前在线人数为:" + getOnlineCount());
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("用户消息:"+chapterId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(message.trim()!=""){
            try {
                System.out.println("消息报文：：：：：");
                System.out.println(message);

                //解析发送的报文
                JSONObject jsonObject = JSONUtil.parseObj(message);
                //存储message
                ChapterContentEntity chapterContentEntity=JSONUtil.toBean(jsonObject,ChapterContentEntity.class);
                Snowflake snowflake = new Snowflake(3L,10L);
                chapterContentEntity.setChapterContentId(snowflake.nextId()+"");
                chapterContentEntity.setStatus(0);
                System.out.println("待存入："+chapterContentEntity);
                websocketDao.insertIntoChapterContent(chapterContentEntity);
//                //追加发送人(防止串改)
//                jsonObject.set("fromChapterId",this.chapterId);
//                String toChapterId=jsonObject.get("toChapterId")+"";
//                //传送给对应toChapterId用户的websocket
//                if(toChapterId!=null && toChapterId.trim()!=null &&webSocketMap.containsKey(toChapterId)){
//                    webSocketMap.get(toChapterId).sendMessage(jsonObject+"");
//                }else{
//                    System.out.println("请求的chapterId:"+toChapterId+"不在该服务器上");
//                    //否则不在这个服务器上，发送到mysql或者redis
//                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("用户错误:"+this.chapterId+",原因:"+error.getMessage());
        error.printStackTrace();
    }


    public void sendInfo(String message, String chapterId) throws IOException {
        System.out.println("发送消息到:"+chapterId+"，报文:"+message);
        if(chapterId!=null&&chapterId.trim()!=null&&webSocketMap.containsKey(chapterId)){
            webSocketMap.get(chapterId).sendMessage(message);

        }else{
            System.out.println("用户"+chapterId+",不在线！");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebsocketController.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketController.onlineCount--;
    }

}
